﻿using System;
using System.Diagnostics;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;

namespace Coding4Fun.MissionControl.WP.Network
{
    public class SocketClient : SocketConnectorBase
    {
        StreamSocket _socket;

        public SocketClient()
        {
            _socket = new StreamSocket();
        }

        public SocketClient(StreamSocket socket)
        {
            _socket = socket;
        }

        public void Cancel()
        {
            _socket.Dispose();
            _socket = null;
        }

        public async void Connect(string hostName, int portNumber)
        {
            try
            {
                await _socket.ConnectAsync(new HostName(hostName), portNumber.ToString(), SocketProtectionLevel.PlainSocket);
                OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = true });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false });
            }
        }

        public async void Send(string dataToSend)
        {
            try
            {
                using (DataWriter writer = new DataWriter(_socket.OutputStream))
                {
                    // Write the length of the binary data that is being
                    // sent to the client.
                    writer.WriteUInt32((UInt32)dataToSend.Length);
                    writer.WriteString(dataToSend);

                    // Send the actual data.
                    await writer.StoreAsync();

                    writer.DetachStream();

                    OnSendCompleted(true);
                }
            }
            catch
            {
                _socket.Dispose();
                _socket = null;

                OnSendCompleted(false);
            }
        }
    }
}
